﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using SharepointSolutionInstaller.Views;
using SharepointSolutionInstaller.Resources;
using SharepointSolutionInstaller.Utils.Configuration;


namespace SharepointSolutionInstaller.Utils.SolutionDeployment
{
    public class ActivateSiteCollectionFeatureCommand : SiteCollectionFeatureCommand
    {
        public readonly IList<SPSite> siteCollections;
        List<Guid?> currentfeatureIds;
        public ActivateSiteCollectionFeatureCommand(InstallProcess parent, IList<SPSite> siteCollections,List<Guid?> featureIds)
            : base(parent)
        {
            this.currentfeatureIds = featureIds;
            this.siteCollections = siteCollections;
        }

        internal override string Description
        {
            // Modif JPI - Début
            get
            {
                return String.Format(CommonUIStrings.activateSiteCollectionFeatureCommand, siteCollections.Count, siteCollections.Count == 1 ? String.Empty : "s");
            }
            // Modif JPI - Fin
        }

        protected internal override bool Execute()
        {
            try
            {
                // Modif JPI - Début
                List<Guid?> featureIds = currentfeatureIds;
                if (siteCollections != null && featureIds != null && featureIds.Count > 0)
                {
                    log.Info(CommonUIStrings.logFeatureActivate);
                    foreach (SPSite siteCollection in siteCollections)
                    {
                        foreach (Guid? featureId in featureIds)
                        {
                            if (featureId == null) continue;
                            SPFeature feature = siteCollection.Features.Add(featureId.Value);
                            //SPFeature feature = siteCollection.Features.Add(featureId.Value, true);

                            log.Info(siteCollection.Url + " : " + featureId.Value.ToString());
                        }
                    }
                }

                return true;
                // Modif JPI - Fin
            }

            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }

        protected internal override bool Rollback()
        {
            DeactivateFeature(siteCollections, currentfeatureIds);
            return true;
        }
    }
}
